<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
if (!function_exists('url')) {
    /**
     * Url生成
     * @param string      $url    路由地址
     * @param array       $vars   变量
     * @param bool|string $suffix 生成的URL后缀
     * @param bool|string $domain 域名
     */
    function url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        return \think\facade\Route::buildUrl($url, $vars)->suffix($suffix)->domain($domain)->build();
    }
}

if (!function_exists('push_wx_message')){
    function push_wx_message($message){
        $url = "http://push.ijingniu.cn/send?key=9a7596908d73470a96625077f71abd08&head=虎课信息&body=$message";

        file_get_contents($url);
    }
}

if (!function_exists('isMobile')){

    function isMobile(){
        // 如果有Http_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])){
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA'])){
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])){
            $clientkeywords = array ('nokia',
                'sony',
                'eriCSSon',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))){
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])){
            // 如果只支持wml并且不支持HTML那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))){
                return true;
            }
        }
        return false;
    }
}

if (!function_exists('http_post')) {
    function http_post($url = '', $postfields = [], $headers = [], $time_out = 15, $gzip = true, $save_file = false)
    {
        global $_G;
        $headers = array_merge([
            'CmsAuthor'        => 'NanBoWan',
            'CmsAuthorQQ'      => '3555990206',
            'X-Requested-With' => 'XMLHttpRequest',
        ], $headers);
        $header = [];
        foreach ($headers as $key => $value) {
            $header[] = $key . ': ' . $value;
        }

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, $time_out);
        curl_setopt($curl, CURLOPT_URL, rtrim($_G['setting']['api_domain'], '/') . '/' . ltrim($url, '/'));
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36");

        curl_setopt($curl, CURLOPT_POST, true);
        if (is_array($postfields)) {
            $postfields = array_merge([
                'auth_qq'       => \think\facade\Config::get('app.auth_qq'),
                'auth_site_url' => \think\facade\Request::domain(),
                'auth_token'    => \think\facade\Config::get('app.auth_token'),
            ], $postfields);
        }
        if (!empty($postfields)) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, is_array($postfields) ? http_build_query($postfields) : $postfields);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        if ($gzip == true) {
            curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        if ($save_file !== false) {
            if (is_file($save_file)) {
                unlink($save_file);
            }
            $fp = fopen($save_file, 'w');
            fwrite($fp, $response);
            fclose($fp);
            if (is_file($save_file)) {
                return ['code' => 1, 'msg' => '更新包下载成功'];
            }
            return ['code' => 0, 'msg' => '更新包存储失败，请检查目录权限'];
        }
        //var_dump($response);
        $result = json_decode($response, true);
        if (is_array($result)) {
            if (!isset($result['code'])) {
                $result['code'] = 1;
            }
            if (!isset($result['debug'])) {
                $result['debug'] = $response;
            }
            return $result;
        }
        return ['code' => 0, 'msg' => '解析失败，请联系管理员', 'debug' => $response];
    }
}


if (!function_exists('show_error')) {
    function show_error($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [], string $tpl = 'common@common/showmessage')
    {
        return showmessage($msg, $url, -1, $data, $wait, $header, $tpl);
    }
}
if (!function_exists('show_info')) {
    function show_info($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [], string $tpl = 'common@common/showmessage')
    {
        return showmessage($msg, $url, 0, $data, $wait, $header, $tpl);
    }
}
if (!function_exists('show_success')) {
    function show_success($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [], string $tpl = 'common@common/showmessage')
    {
        return showmessage($msg, $url, 1, $data, $wait, $header, $tpl);
    }
}
if (!function_exists('show_loading')) {
    function show_loading($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [], string $tpl = 'common@common/showmessage')
    {
        return showmessage($msg, $url, 2, $data, $wait, $header, $tpl);
    }
}

if (!function_exists('showmessage')) {
    function showmessage($msg = '', string $url = null, int $code = 0, $data = '', int $wait = 3, array $header = [], string $tpl = 'common@common/showmessage')
    {
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } else if ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : url($url);
        }
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
            'url'  => $url,
            'wait' => $wait,
        ];
        $type     = \think\facade\Request::isAjax() ? 'json' : 'html';
        $response = \think\Response::create($result, $type)->header($header);
        if ($type === 'html') {
            $response->data(\think\facade\View::assign($result)->fetch($tpl));
        }
        throw new \think\exception\HttpResponseException($response);
        exit;
    }
}
if (!function_exists('redirect')) {
    /**
     * 获取\think\response\Redirect对象实例
     * @param  mixed         $url    重定向地址 支持Url::build方法的地址
     * @param  array|integer $params 额外参数
     * @param  int           $code   状态码
     * @return \think\response\Redirect
     */
    function redirect($url = [], $params = [], $code = 302, $header = [], $with = [])
    {
        if (is_integer($params)) {
            $code   = $params;
            $params = [];
        }

        throw new \think\exception\HttpResponseException(\think\Response::create($url, 'redirect', $code)->params($params)->header($header)->with($with));
    }
}

if (!function_exists('authcode')) {
    function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
    {
        $ckey_length = 4;
        $key         = md5($key != '' ? $key : \think\facade\Config::get('app.authkey'));
        $keya        = md5(substr($key, 0, 16));
        $keyb        = md5(substr($key, 16, 16));
        $keyc        = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

        $cryptkey   = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);

        $string        = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);

        $result = '';
        $box    = range(0, 255);

        $rndkey = array();
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }

        for ($j = $i = 0; $i < 256; $i++) {
            $j       = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp     = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a       = ($a + 1) % 256;
            $j       = ($j + $box[$a]) % 256;
            $tmp     = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }

        if ($operation != 'DECODE') {
            return $keyc . str_replace('=', '', base64_encode($result));
        }
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        }
        return '';
    }
}

if (!function_exists('create_dir')) {
    function create_dir($dir = '', $mode = 0777, $makeindex = true)
    {
        if (!empty($dir) && !is_dir($dir)) {
            create_dir(dirname($dir), $mode, $makeindex);
            @mkdir($dir, $mode);
            if (!empty($makeindex)) {
                @touch($dir . DIRECTORY_SEPARATOR . 'index.html');
                @chmod($dir . DIRECTORY_SEPARATOR . 'index.html', 0777);
            }
        }
        return true;
    }
}

if (!function_exists('delete_dir')) {
    function delete_dir($dir = '')
    {
        if (empty($dir) || !is_dir($dir)) {
            return false;
        }
        foreach (scandir($dir) as $entry) {
            if (in_array($entry, ['.', '..'])) {
                continue;
            }
            $filename = $dir . DIRECTORY_SEPARATOR . $entry;
            if (is_dir($filename)) {
                delete_dir($filename);
            } else {
                @unlink($filename);
            }
        }
        @rmdir($dir);
        return true;
    }
}

if (!function_exists('format_bytes')) {
    function format_bytes($size = 0)
    {
        $units = [' B', ' KB', ' MB', ' GB', ' TB'];
        for ($i = 0; $size >= 1024 && $i < 4; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $units[$i];
    }
}

if (!function_exists('replace_random_str')) {
    function replace_random_str($str = '')
    {

        $j_all = substr_count($str, '@');
        $k_all = substr_count($str, '#');
        $h_all = substr_count($str, '*');
        for ($j = 0; $j < $j_all; $j++) {
            $str = preg_replace_callback('/\@/', function () {
                $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $l   = mt_rand(0, 25);
                return $str[$l];
            }, $str, 1);
        }
        for ($k = 0; $k < $k_all; $k++) {
            $str = preg_replace_callback('/\#/', function () {
                $str = '0123456789';
                $l   = mt_rand(0, 9);
                return $str[$l];
            }, $str, 1);
        }
        for ($h = 0; $h < $h_all; $h++) {
            $str = preg_replace_callback('/\*/', function () {
                $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
                $l   = mt_rand(0, 35);
                return $str[$l];
            }, $str, 1);
        }
        return $str;
    }
}

if (!function_exists('random')) {
    function random($length = 10, $numeric = 0)
    {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        $hash = '';
        if (!$numeric) {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed{mt_rand(0, $max)};
        }
        return $hash;
    }
}

if (!function_exists('cutstr')) {
    function cutstr($string, $length = 80, $dot = ' ...')
    {
        if (strlen($string) <= $length) {
            return $string;
        }

        $pre    = chr(1);
        $end    = chr(1);
        $string = str_replace(['&amp;', '&quot;', '&lt;', '&gt;'], [$pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end], $string);

        $strcut = '';
        $n      = $tn      = $noc      = 0;
        while ($n < strlen($string)) {

            $t = ord($string[$n]);
            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1;
                $n++;
                $noc++;
            } elseif (194 <= $t && $t <= 223) {
                $tn = 2;
                $n += 2;
                $noc += 2;
            } elseif (224 <= $t && $t <= 239) {
                $tn = 3;
                $n += 3;
                $noc += 2;
            } elseif (240 <= $t && $t <= 247) {
                $tn = 4;
                $n += 4;
                $noc += 2;
            } elseif (248 <= $t && $t <= 251) {
                $tn = 5;
                $n += 5;
                $noc += 2;
            } elseif ($t == 252 || $t == 253) {
                $tn = 6;
                $n += 6;
                $noc += 2;
            } else {
                $n++;
            }

            if ($noc >= $length) {
                break;
            }

        }
        if ($noc > $length) {
            $n -= $tn;
        }

        $strcut = substr($string, 0, $n);
        $strcut = str_replace([$pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end], ['&amp;', '&quot;', '&lt;', '&gt;'], $strcut);

        $pos = strrpos($strcut, chr(1));
        if ($pos !== false) {
            $strcut = substr($strcut, 0, $pos);
        }
        return $strcut . $dot;
    }
}
